# !/usr/bin/python
# -*-coding:utf-8 -*-
"""
@File    :   httpclient.py
@Create  :   2021/9/28 14:29
@Author  :   David
"""
import requests
import json as jsn


class HttpClient:

    def __init__(self):
        self.header = {
            "Content-Type": "application/json; charset=utf-8",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/92.0.4515.159 Safari/537.36 "
        }
        self.session = requests.session()

    def get(self, url, **kwargs):
        return self.send_request(url, "GET", **kwargs)

    def post(self, url, data=None, json=None, **kwargs):
        return self.send_request(url, "POST", data, json, **kwargs)

    def put(self, url, data=None, **kwargs):
        return self.send_request(url, "PUT", data, **kwargs)

    def delete(self, url, **kwargs):
        return self.send_request(url, "DELETE", **kwargs)

    def patch(self, url, data=None, **kwargs):
        return self.send_request(url, "PATCH", data, **kwargs)

    def send_request(self, url, method, data=None, json=None, **kwargs):
        if method.upper() == "GET":
            return self.session.get(url, **kwargs)
        if method.upper() == "POST":
            return self.session.post(url, data, json, **kwargs)
        if method.upper() == "PUT":
            if json:
                # PUT 和 PATCH 中没有提供直接使用json参数的方法，因此需要用data来传入
                data = jsn.dumps(json)
            return self.session.put(url, data, **kwargs)
        if method.upper() == "DELETE":
            return self.session.delete(url, **kwargs)
        if method.upper() == "PATCH":
            if json:
                data = jsn.dumps(json)
            return self.session.patch(url, data, **kwargs)


hc = HttpClient()
